package com.itheima.social.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.social.entity.SoUser;
import com.itheima.social.common.R;
import com.itheima.social.service.SoUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import java.util.Random;

@RestController
@RequestMapping("/social/api")
@Slf4j
public class SoUserController {

    @Autowired
    private SoUserService soUserService;

    @Value("${social.path}")
    private String basePath;

    @PostMapping("/user_api.php")
    @Transactional
    public R<Object> user_api(@RequestParam(required = false) String act, @RequestParam(required = false) String ruser, @RequestParam(required = false) String remail,
                              @RequestParam(required = false) String rpwd, @RequestParam(required = false) String rsex, @RequestParam(required = false) String rphone,
                              @RequestParam(required = false) String rdesc,

                              @RequestParam(required = false) String uid,
                              @RequestParam(required = false) String pic, @RequestParam(required = false) String myname, @RequestParam(required = false) String mysex,
                              @RequestParam(required = false) String myphone, @RequestParam(required = false) String myemail, @RequestParam(required = false) String mydesc,

                              @RequestParam(required = false) String phone, @RequestParam(required = false) String pwd, @RequestParam(required = false) String verify
    ) throws IOException {
        if (act != null) {
            if (act.equals("reg")) {
                LambdaQueryWrapper<SoUser> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(remail != null, SoUser::getEmail, remail).or()
                        .eq(rphone != null, SoUser::getPhone, rphone);
                SoUser user = soUserService.getOne(queryWrapper);

                if (user != null) {
                    String email = user.getEmail();
                    String n = remail.equals(email) ? "邮箱" : "手机号";
                    return R.error(n + "已被注册");
                }

                SoUser soUser = new SoUser();
                soUser.setNickname(ruser);
                soUser.setEmail(remail);
                soUser.setPwd(rpwd);
                soUser.setSex(rsex);
                soUser.setPhone(rphone);
                soUser.setDescs(rdesc);
                soUserService.save(soUser);
                return R.success("注册成功");
            } else if (act.equals("login")) {
                LambdaQueryWrapper<SoUser> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(phone != null, SoUser::getPhone, phone).eq(pwd != null, SoUser::getPwd, pwd);
                SoUser soUser = soUserService.getOne(queryWrapper);
                if (soUser == null) {
                    return R.error("手机号或密码错误");
                }
                return R.success(soUser);
            } else if (act.equals("update")) {
                SoUser soUser = new SoUser();
                soUser.setPhone(myphone);
                soUser.setNickname(myname);
                soUser.setEmail(myemail);
                soUser.setSex(mysex);
                soUser.setDescs(mydesc);
                if (StringUtils.isNotEmpty(pic)) {
                    String[] parts = pic.split(",");
                    String fileData = parts[1];
                    byte[] fileBytes = Base64.getDecoder().decode(fileData.getBytes(StandardCharsets.UTF_8));

                    Date currentTime = new Date();
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
                    String dateString = formatter.format(currentTime);

                    Random random = new Random();
                    int number = random.nextInt(90000) + 10000;

                    String name = dateString + number + ".png";

                    soUser.setPhoto(name);
                    Files.write(Paths.get(basePath + name), fileBytes);
                }

                LambdaQueryWrapper<SoUser> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(uid != null, SoUser::getUid, uid);
                boolean update = soUserService.update(soUser, queryWrapper);
                if (update) {
                    SoUser user = soUserService.getOne(queryWrapper);
                    return R.success(user);
                }
            }
        }

        LambdaQueryWrapper<SoUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(uid != null, SoUser::getUid, uid);
        SoUser user = soUserService.getOne(queryWrapper);
        return R.success(user);
    }

}
